import axios from 'axios'
import {Message} from 'element-ui'
import $url from './url.js'

//得到url
let baseURL=$url.baseUrl

// 创建实例
const service=axios.create({
    baseURL:baseURL,
    //请求超时时间
    timeout:5000
})

//请求拦截
service.interceptors.request.use(
    config=>{
        //如果token存在则配置统一的请求头  
        const isLogin = localStorage.getItem('tokenKey') ? true : false
        if(isLogin){
            config.headers.Authorization = localStorage.getItem('tokenKey')
        }
        return config
    },error=>{
        return Promise.reject(error)
    }
)

//响应拦截
service.interceptors.response.use(
    response=>{
        if(response.data && response.data.code){
            switch(response.data.code){
                case 599:
                    Message.warning(response.data.msg || response.data)
                break;
                // token处理
                case 598:
                    Message.warning(response.data.msg)
                    // 失效的时候，先清除，再去登录页
                    localStorage.removeItem('tokenKey')
                    localStorage.removeItem('by_menu')
                    location.href = '/login'
                break;
                default:
                break;
            }
        }
        return response.data
    },error=>{
        
        return Promise.reject(error)
    }
)

//定义请求加载动画
// let loading = ''
// function startLoading() {
//     loading=Loading.service({
//         // 锁定
//         lock:true,
//         text:'拼命加载中...',
//         background:'rgba(0,0,0,.7)'
//     })
// }
// function endLoading() {
//     loading.close()
// }

export default service